import router from "@/router";
import { nativeplacestore } from "./utils/base";
import { gettree, getUserInfo } from "@/http/api.js";
let g;
router.beforeEach(async (to, from, next) => {
  let routerLen = router.options.routes.length == 3;
  let token = nativeplacestore.get("login");

  if (routerLen && to.path !== "/login" && token && !g) {
    let userInfo = await getUserInfo();
    let usertree = await gettree({ type: 3 });

    if (userInfo && usertree) {
      nativeplacestore.set("usertree2", usertree.data);
      usertree = usertree.data.filter((v) => {
        return v.parentId !== 0;
      });

      nativeplacestore.set("userInfo", userInfo);
      nativeplacestore.set("usertree", usertree);

      usertree.forEach((v) => {
        let obj = {
          path: v.path,
          name: v.path,
          component: routerCom(v.component),
        };
        router.addRoute("home", obj);
      });
      g = 1;
      next({
        path: to.path,
        replace: true,
      });
    } else {
      next({
        path: "/login",
        replace: true,
      });
    }
  } else {
    next();
  }
});

function routerCom(view) {
  return (resolve) => require([`@/views/${view}.vue`], resolve);
}
